package lagou.homework.docker.controller;

import lagou.homework.docker.entity.Tbstudent;
import lagou.homework.docker.repository.StudentRepository;
import lagou.homework.docker.utils.Response;
import lagou.homework.docker.utils.ResponseResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Resource
    private StudentRepository studentRepository;

    @PostMapping("/save")
    public ResponseResult sayHello(@RequestBody Tbstudent tbstudent) {
        try {
            Tbstudent save = studentRepository.save(tbstudent);
            return Response.success("添加成功",save);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("添加失败" ,e.getMessage());
        }
    }


    @GetMapping("/findByUserName")
    public ResponseResult queryUsers(String username) {
        try {
           return Response.success("查询成功",studentRepository.findTbstudentByUsername(username));
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("查询失败",e.getMessage());
        }
    }

    @GetMapping("/list")
    public ResponseResult list() {
        try {
            return Response.success("查询成功",studentRepository.findAll());
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("查询失败",e.getMessage());
        }
    }


    @DeleteMapping("/delete")
    public ResponseResult delete(Integer id) {
        try {
            studentRepository.deleteById(id);
            return Response.success("删除成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("删除失败",null);
        }
    }
}
